import 'package:dio/dio.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import 'common_util.dart';
import 'navigator_util.dart';
import 'store_util.dart';

class HttpUtil {
  Dio dio = Dio();

  HttpUtil.privateConstructor() {
    dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
      String url = '';
      if (options.path.isNotEmpty) {
        url = options.path;
      }

      if (!url.contains(CommonUtil.getEnvConfig()["baseUrl"])) {
        url = CommonUtil.getEnvConfig()["bizUrl"] + url;
      }

      options.path = url;

      options.contentType = url.lastIndexOf('/upload') > 0
          ? 'multipart/form-data'
          : 'application/json';
      options.headers["token"] = StoreUtil.getToken();
      options.headers["clienttype"] = CommonUtil.getEnvConfig()["clientType"];
      options.headers["sdklanguage"] = CommonUtil.getEnvConfig()["language"];

      options.data ??= {};
      bool useSpinning = true;
      if (options.data.runtimeType == FormData) {
        FormData formData = options.data as FormData;
        if (formData.fields.isNotEmpty) {
          for (var field in formData.fields) {
            if (field.key == 'useSpinning' && "false"==field.value) {
              useSpinning = false;
              break;
            }
          }
        }
      } else {
        useSpinning = (null != options.data &&
                null != options.data["useSpinning"] &&
                false == options.data["useSpinning"])
            ? false
            : true;
      }

      if (useSpinning) {
        SmartDialog.showLoading(msg: "加载中..");
      }

      return handler.next(options);
    }, onResponse: (response, handler) {
      SmartDialog.dismiss();
      print(response);

      var res = response.data;
      res["isSuccess"] =
          (null != response.data && response.data["code"] == "0000")
              ? true
              : false;

      if (res["code"] == "9001") {
        CommonUtil.showToast("登录凭证失效，请重新登录");
        NavigatorUtil.pushLoginAndRemoveUntil();
        return;
      }

      if (res["code"] == "9005" ||
          res["code"] == "F007" ||
          res["code"] == "F013") {
        CommonUtil.showToast(res["msg"]);
        return;
      }

      response.data = res;
      handler.next(response);
    }, onError: (DioError e, handler) {
      SmartDialog.dismiss();
      CommonUtil.showToast("发生了错误: ${e.message}");
      return handler.next(e);
    }));
  }

  static final instance = HttpUtil.privateConstructor();

  factory HttpUtil.getInstance() => instance;

  static Dio getDio() {
    return instance.dio;
  }
}
